/**
 * 
 */
package com.wistech.search.solr.extend;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.request.SolrQueryRequest;

import com.wistech.utils.MathUtils;

/**
 * @author Liuye
 * 
 */
public class SolrIndexContext {
	private SolrQueryRequest request;
	private SolrInputDocument document;
	private Map<String, Object> model = new HashMap<String, Object>();
	private String idName = "id";

	public SolrIndexContext(SolrQueryRequest req) {
		this.request = req;
	}

	public SolrIndexContext(SolrQueryRequest request,
			SolrInputDocument document, String idName) {
		this.request = request;
		this.document = document;
		this.idName = idName;
	}

	public Map<String, Object> getModel() {
		return model;
	}

	public void setModel(Map<String, Object> model) {
		this.model = model;
	}

	/**
	 * @return the request
	 */
	public SolrQueryRequest getRequest() {
		return request;
	}

	/**
	 * @param request
	 *            the request to set
	 */
	public void setRequest(SolrQueryRequest request) {
		this.request = request;
	}

	/**
	 * @return the document
	 */
	public SolrInputDocument getDocument() {
		return document;
	}

	/**
	 * @param document
	 *            the document to set
	 */
	public void setDocument(SolrInputDocument document) {
		this.document = document;

	}

	/**
	 * @return the idName
	 */
	public String getIdName() {
		return idName;
	}

	/**
	 * @param idName
	 *            the idName to set
	 */
	public void setIdName(String idName) {
		this.idName = idName;
	}

	public void handleDocumentWithPrefix(String prefix) {
		String idFieldName = request.getSchema().getUniqueKeyField().getName();
		SolrInputField idInputField = document.getField(idFieldName);
		if (idInputField == null) {
			String msg = "the document missing uniqueKey field value.";
			throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
		}
		model.put(idName, idInputField.getValue());
		for (Map.Entry<String, SolrInputField> entry : document.entrySet()) {
			String fieldName = entry.getKey();
			if (!fieldName.equals(idName)) {
				Object fieldValue = entry.getValue().getValue();
				if (StringUtils.isNotBlank(prefix)
						&& fieldName.startsWith(prefix)) {
					fieldName = fieldName.substring(prefix.length());
				}
				model.put(fieldName, fieldValue);
			}
		}
	}

}
